<template>
  <div class="json-editor">
    <textarea ref="textarea"/>
  </div>
</template>

<script>
import CodeMirror from 'codemirror'
import 'codemirror/addon/lint/lint.css'
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/rubyblue.css'
import 'codemirror/theme/tomorrow-night-bright.css'
require('script-loader!jsonlint')
import 'codemirror/mode/javascript/javascript'
import 'codemirror/addon/lint/lint'
import 'codemirror/addon/lint/json-lint'
export default {
  name: 'JsonEditor',
  /* eslint-disable vue/require-prop-types */
  // props: ['value'],
  props: {
    value: {
      type: String | Object,
      required: true,
      'default': () => ''
    },
    readOnly:{
      readOnly: Boolean,
      'default': false
    }
  },
  data() {
    return {
      jsonEditor: false
    }
  },
  watch: {
    value(value) {
      const editor_value = this.jsonEditor.getValue()
      if (value !== editor_value) {
        this.jsonEditor.setValue(JSON.stringify(this.value, null, 4))
      }
    }
  },
  mounted() {
    // this.value = JSON.parse(this.value)
    this.jsonEditor = CodeMirror.fromTextArea(this.$refs.textarea, {
      tabSize: 2,
      lineNumbers: true,
      mode: 'application/json',
      gutters: ['CodeMirror-lint-markers'],
      theme: 'tomorrow-night-bright',
      lint: true,
      autoRefresh: true,
      lineWrapping: true,
      readOnly: this.readOnly
    })
    this.jsonEditor.setValue(JSON.stringify(this.value, null, 4))
    this.jsonEditor.on('change', cm => {
      this.$emit('changed', cm.getValue())
      this.$emit('input', cm.getValue())
    })
  },
  methods: {
    refresh() {
      this.jsonEditor.refresh()
    },
    getValue() {
      return this.jsonEditor.getValue()
    }
  }
}
</script>

<style scoped>
.json-editor{
  height: 100%;
  position: relative;
}
.json-editor >>> .CodeMirror {
  height: auto;
  min-height: 200px;
}
.json-editor >>> .CodeMirror-scroll{
  min-height: 200px;
}
.json-editor >>> .cm-s-rubyblue span.cm-string {
  color: #F08047;
}
.json-editor >>> .CodeMirror-linenumber {
  line-height: 20px;
}
.json-editor >>> .CodeMirror-gutter-elt{
  line-height: 20px;
}
.json-editor >>> .CodeMirror-line {
  line-height: 20px;
}
</style>